<?php

namespace App\Models;

use app\common\model\ReservationApplyModel;
use app\common\model\ReservationScheduleModel;
use app\common\model\ReservationSpecialScheduleModel;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ScoreRuleController;
use Exception;
use http\Env\Request;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * 空间预约远程操作
 * Class ReservationModel
 * @package app\common\model
 */
class StudyRoomReservationRemoteOperation extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = 'study_room_reservation_remote_operation';



    /**
     * 书房预约远程操作列表
     *  @param limit int 分页大小
     *  @param reservation_id 门禁id
     *  @param type 类型  1 远程开门   6 下载白名单； 7 清空本地所有白名单；
     *  @param status 类型  状态   1 已成功 2 处理中 3待处理 
     *  @param start_time int 开始时间
     *  @param end_time int 结束时间
     *  @param keywords string 搜索筛选
     */
    public function lists($field = null, $reservation_id = null, $keywords = null, $type = null, $status = null, $start_time = null, $end_time = null, $limit = 10)
    {
        if (empty($field)) {
            $field = ['o.id', 'r.name as reservation_name', 'o.order_number', 'o.type', 'o.reservation_id', 'o.cab_code', 'o.status', 'o.account', 'o.manage_id', 'o.create_time'];
        }
        $res = $this->from($this->getTable() . ' as o')
            ->select($field)
            ->join('study_room_reservation as r', 'r.id', '=', 'o.reservation_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('o.cab_code', 'like', "%$keywords%")->orWhere('r.name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($reservation_id, $start_time, $end_time, $type, $status) {
                if ($reservation_id) {
                    $query->where('reservation_id', $reservation_id);
                }
                if ($type) {
                    $query->where('o.type', $type);
                }
                if ($status) {
                    $query->where('o.status', $status);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('o.create_time', [$start_time, $end_time]);
                }
            })
            ->orderByDesc('o.id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     * 添加远程操作（添加后，交给缓存处理）
     * @param $ids 预约id all表示全部，类型为 1，不能全部执行
     * @param $node 操作平台，1、前台用户  2 、后台管理员
     */
    public function add($ids, $type = null, $user_id = null, $node = 2)
    {
        if ($type == 1 && (empty($ids) || $ids == 'all')) {
            throw new Exception("远程开门必须选择设备");
        }

        $ids =  $ids != 'all' ? explode(',', $ids) : '';

        $res = StudyRoomReservation::where(function ($query) use ($ids) {
            if ($ids) {
                $query->whereIn('id', $ids);
            }
        })->where('is_del', 1)
            ->get();

        if (empty($res)) {
            throw new Exception("暂无可用设备");
        }

        $data = [];
        foreach ($res as $key => $val) {
            $data[$key]['order_number'] = date('ymdHis') . get_rnd_number(5);
            $data[$key]['type'] = $type;
            $data[$key]['node'] = $node;
            $data[$key]['reservation_id'] = $val['id'];
            $data[$key]['cab_code'] = $val['cab_code'];
            $data[$key]['create_time'] = date('Y-m-d H:i:s');
            $data[$key]['change_time'] = date('Y-m-d H:i:s');
            $data[$key]['status'] = 3; //3待处理  2 处理中  1 已成功
            $data[$key]['user_id'] = $node == 1 ? $user_id : 0; //管理员
            $data[$key]['manage_id'] = $node == 2 ? request()->manage_id : 0; //管理员

            Cache::increment($val['cab_code']); //增加一次次数
        }
        return $this->insert($data);
    }
}
